<?php

/**
 * @version			$Id$
 * @create 			2012-04-25 12:04:22 By xjiujiu
 * @package 	 	app.admin
 * @subpackage 	 	action
 * @copyRight 		Copyright (c) 2011-2012 http://www.xjiujiu.com.All right reserved
 * HongJuZi Framework
 */
defined('_HEXEC') or die('Restricted access!');

//导入引用文件
HClass::import('config.popo.adminuserpopo, app.admin.action.adminaction, model.adminusermodel');

/**
 * 用户列表的动作类 
 * 
 * 主要处理后台管理主页的相关请求动作 
 * 
 * @author 			xjiujiu <xjiujiu@foxmail.com>
 * @package 		app.admin.action
 * @since 			1.0.0
 */
class AdminuserAction extends AdminAction
{

    /**
     * 构造函数 
     * 
     * 初始化类变量 
     * 
     * @access public
     */
    public function __construct() 
    {
        parent::__construct();
        $this->_popo        = new AdminuserPopo();
        $this->_model       = new AdminuserModel($this->_popo);
    }

    /**
     * 搜索方法 
     * 
     * @access public
     */
    public function search()
    {
        $this->_search($this->_combineWhere());
        $this->_render('adminuser/list');
    }

    /**
     * 主页动作 
     * 
     * @access public
     */
    public function index()
    {        
        $this->_search();
        $this->_render('adminuser/list');
    }

    /**
     * 全称为CheckUserName即检测当前的用户名 
     * 
     * 当用户名存在时给出错误的提示 
     * 
     * @access public
     */
    public function isunused()
    {
        HVerify::isAjax();
        HVerify::isEmpty(HRequest::getParameter('name'), '用户名');
        if(true === $this->_model->isUserNameUsed($userName)) {
            throw new HVerifyException('用户名已经使用！');
        }
        HResponse::json(array('rs' => true, 'message' => '可以使用！'));
    }

    /**
     * 执行模块的添加 
     * 
     * @access public
     */
    public function add()
    {
        HVerify::isStrLen(HRequest::getParameter('password'), '登录密码', 6, 20);
        $this->_otherJobsBeforeEdit();
        $this->_formatFieldData();
        $this->_verifyLoginNameAndEmail();
        $this->_add();

        if(HVerify::isAjaxByBool()) {
            HResponse::json(array(
                'rs' => true, 
                'message' => '新' . $this->_popo->modelZhName . '添加成功！', 'nextUrl' => $this->_getReferenceUrl(1))
            );
            return;
        }
        HResponse::succeed('新' . $this->_popo->modelZhName . '添加成功！', $this->_getReferenceUrl(1));
    }

    /**
     * 检测用户名或邮箱是否已经使用
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access private
     * @param $id 用户编号，默认为NULL表示为新加
     * @throws HVerifyException 验证异常
     */
    private function _verifyLoginNameAndEmail($id = null)
    {
        $where  = '(`name` = \'' . HRequest::getParameter('name') . '\'';
        if(HRequest::getParameter('email')) {
            $where  .= ' OR `email` = \'' . HRequest::getParameter('email') . '\'';
        } 
        if(HRequest::getParameter('phone')) {
            $where  .= ' OR `phone` = \'' . HRequest::getParameter('phone') . '\'';
        }
        $where  .= ' OR 1 = 2)';
        if($id) {
            $where  .= ' AND `id` != ' . $id;
        }
        $record     = $this->_model->getRecordByWhere($where);
        if(!$record) {
            return;
        }
        if($record['name'] == HRequest::getParameter('name')) {
            throw new HVerifyException('用户名已经使用！');
        }
        if($record['phone'] && $record['phone'] == HRequest::getParameter('phone')) {
            throw new HVerifyException('电话号码已经使用！');
        }
        if($record['email'] && $record['email'] == HRequest::getParameter('email')) {
            throw new HVerifyException('邮箱已经使用！');
        }
    }

    /**
     * 格式化字段数据
     * 
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access private
     */
    private function _formatFieldData($isEdit = false)
    {
        $salt   = HRequest::getParameter('salt');
        if(!$salt){
            $salt = rand(10000, 99999);
            HRequest::setParameter('salt', $salt);
        }
        if(HRequest::getParameter('password')) {
            HRequest::setParameter(
                'password', 
                $this->_encodePassword(
                    HRequest::getParameter('password', false),
                    HRequest::getParameter('salt')
                )
            );
        }
        if(HRequest::getParameter('login_time')) {
            HRequest::setParameter('login_time', strtotime(HRequest::getParameter('login_time')));
        }
        $ip     = HRequest::getParameter('ip');
        if(!$ip){
            $ip = HRequest::getClientIp();
            HRequest::setParameter('ip', $ip);
        }
    }

    /**
     * 编辑提示动作 
     * 
     * @access public
     */
    public function edit()
    {
        HVerify::isRecordId(HRequest::getParameter('id'), '用户ID');
        if(HRequest::getParameter('password')) {
            HVerify::isStrLen(HRequest::getParameter('password'), '登录密码', 6, 20);
        } else {
            HRequest::deleteParameter('password');
        }
        $this->_otherJobsBeforeEdit();
        $this->_formatFieldData(true);
        $this->_verifyLoginNameAndEmail(HRequest::getParameter('id'));
        $record     = $this->_edit();

        if(HVerify::isAjaxByBool()) {
            HResponse::json(array(
                'rs' => true, 
                'message' => $this->_popo->modelZhName . '信息更新成功！', 'nextUrl' => $this->_getReferenceUrl(1))
            );
            return;
        }
        HResponse::succeed($this->_popo->modelZhName . '信息更新成功！', $this->_getReferenceUrl(1));
    }

    /**
     * 删除动作 
     * 
     * @access public
     * @exception HRequestException 请求异常
     */
    public function delete()
    {
        $recordIds  = HRequest::getParameter('id');
        if(!is_array($recordIds)) {
            $recordIds  = array($recordIds);
        }
        if(in_array(HSession::getAttribute('id', 'user'), $recordIds)) {
            throw new HRequestException('删除用户中不能包含自己！');
        }
        $this->_delete($recordIds);
        $linkeddata     = HClass::quickLoadModel('linkeddata');
        $linkeddata->setRelItemModel('user', 'openid');
        $linkeddata->deleteByWhere(HSqlHelper::whereIn('rel_id', $ids));
        HResponse::succeed(
            '删除成功！', 
            HResponse::url($this->_popo->modelEnName)
        );
    }

    /**
     * 列表后驱方法
     * @return [type] [description]
     */
    protected function _otherJobsAfterList()
    {
        parent::_otherJobsAfterList();
        HResponse::registerFormatMap('sex', 'name', UserPopo::$sexMap);
    }

    /**
     * 详情后驱方法
     * @return [type] [description]
     */
    protected function _otherJobsAfterInfo()
    {
        parent::_otherJobsAfterInfo();
        HResponse::setAttribute('sex_list', UserPopo::$sexMap);
    }

    /**
     * 异步获取属性规格列表
     * @throws HRequestException
     */
    public function alist()
    {
        HVerify::isAjax();

        $parentId   = HRequest::getParameter('parent_id');
        $perpage    = 100;

        $keyword    = HRequest::getParameter('keyword');
        $where      = '1 = 1';
        if($parentId){
            $where .= ' AND `parent_id` = ' . $parentId;
        }
        if($keyword){
            $where .= ' AND `name` LIKE \'%' . $keyword . '%\'';
        }
        $totalRows  = $this->_model->getTotalRecords($where);
        $totalPages = ceil($totalRows / $perpage);
        $page       = $this->_getPageNumber($totalPages);
        $list       = $this->_model->getListByFields(
            '`id`, `name`, `true_name`, `parent_id`, `phone`',
            $where, $page, $perpage
        );
        $actorMap   = HArray::turnItemValueAsKey($this->_getActorList($list), 'id');
        foreach($list as $key => &$item){
            $item['actor']  = $actorMap[$item['parent_id']] ? $actorMap[$item['parent_id']]['name'] : '未知';
            $item['true_name'] = $item['true_name'] ? $item['true_name'] : '';
            $item['phone'] = $item['phone'] ? $item['phone'] : '';
        }

        HResponse::json(array('rs' => true, 'data' => $list, 'totalPages' => $totalPages));
    }

    /**
     * 获取角色列表
     * @param $list
     * @return Array
     */
    private function _getActorList($list)
    {
        $actor      = HClass::quickLoadModel('actor');
        $actorList  = $actor->getAllRows(HSqlHelper::whereInByListMap('id', 'parent_id', $list));

        return $actorList;
    }

    /**
     * 异步获取用户openid
     */
    public function agetopenid()
    {
        $id         = HRequest::getParameter('id');
        if(HVerify::isEmptyNotZero($id)){
            throw new HRequestException('编号不能为空');
        }
        $record     = $this->_model->getRecordById($id);
        if(!$record){
            throw new HRequestException('记录不存在');
        }
        $linkeddata = HClass::quickLoadModel('linkeddata');
        $linkeddata->setRelItemModel('user', 'openid');
        $info       = $linkeddata->getRecordByWhere('`rel_id` = ' . $record['id']);
        $data       = '该用户还没关注公众号';
        if($info){
            $data = '该用户的openid为：' . $info['item_id'];
        }
        HResponse::json(array('rs' => true, 'data' => $data));
    }

    /**
     * 编辑动作 
     * 
     * @access public
     */
    public function editview()
    {
        global $_W, $_GPC;
        $id     = HRequest::getParameter('id');

        if($id == HSession::getAttribute('id', 'user') 
            && $_W['user']['uid'] && in_array($_W['role'], array('founder', 'ower', 'manager'))) {
            HResponse::info(
                '您当前使用的是微擎账号登陆，如果想使用网站独立账号，请先添加！', 
                HResponse::url('adminuser/addview')
            );
            return;
        }
        $this->_editview();
        $this->_otherJobsAfterInfo();
        $this->_render($this->_popo->modelEnName . '/info');
    }

}
?>
